//
//  Account.swift
//  ModernFoodWebsite
//
//  Created by apple on 16/5/29.
//  Copyright © 2016年 Lonnie. All rights reserved.
//

import Foundation
import CoreData


class Account: NSManagedObject {
    class func currentAccountKey()->String? {
        let defaults = NSUserDefaults.standardUserDefaults()
        return defaults.stringForKey("phone")
    }
    
    
    class func setCurrentAccountKey(key:String){
        let defaults = NSUserDefaults.standardUserDefaults()
        defaults.setObject(key, forKey: "phone")
    }
    
    class func currentAccount()->Account? {
        let phone = classForCoder().currentAccountKey()
        if phone == nil {
            return nil
        }
        let req = NSFetchRequest(entityName: "Account")
        req.predicate = NSPredicate(format: "phone == %@", phone!)
        var user:Account?
        do {
            let users = try DataController.shareInstance.managedObjectContext.executeFetchRequest(req)
            if users.count > 0 {
                user = users.first as? Account
            }
        } catch let error as NSError {
            
        }
        return user
    }
    
    class func clearCurrentAccount() {
        let defaults = NSUserDefaults.standardUserDefaults()
        defaults.removeObjectForKey("phone")
    }
    
    class func isLogin()->Bool{
        return self.currentAccount() != nil
    }

}
